package com.example.shiro.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.shiro.dao.SysUserRepository;
import com.example.shiro.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/es")
public class EsController {
    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/save")
    public Boolean save(){
        SysUser user = new SysUser();
        String result = redisTemplate.opsForValue().get(SecurityUtils.getSubject().getPrincipal());
        JSONObject jsonObject = JSON.parseObject(result);
        BeanUtil.copyProperties(jsonObject,user);
        user.setId((int)(Math.random() * 10000));
        sysUserRepository.save(user);
        return true;
    }


    @RequestMapping("/get")
    @RequiresPermissions("index:select")
    @RequiresRoles("admin")
    public Iterable<SysUser> get(){
       return sysUserRepository.findAll();
    }

    @RequestMapping("/delete/{id}")
    public Boolean delete(@PathVariable Long id){
        sysUserRepository.deleteById(id);
        return true;
    }
}
